// pages/my/orderlist/orderdetail/orderdetail.js
import { axios }  from '../../../../utils/ajax.js'
import { gettime } from '../../../../utils/djs.js'
let app = getApp()
let shareImg;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    data:'',
    timetips:'',
    //默认收缩的物流信息高度
    loghideheight:'',
    initialheight:'',
    statename:'',
    loglist:[],
    orderno:'',
    orderid: '',
    userid: '',
    token: '',
    iPhoneX:false,
    //是否显示重新购买按钮
    showbuyagain:false,
    //是否显示拼团分享弹窗
    groupwindowshow:false,
    maskstate:false,
    goodsdata: [],
    grouptimetips:'',
    returnbox: false,
    //需要人数的图片
    needPeopleicon:[],
    needPeople:'',
    //拼团需要总人数 （还差人数+ 已拼人数）
    totlegrouplength: 0,
    //一个移动块的宽度
    movablewidth:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.model.substr(0, 8) == 'iPhone X') {
      this.setData({
        iPhoneX: true
      })
    }
    this.getData(options);

    //读取猜你喜欢数据
    // axios({
    //   url: '/goods/guessLike'
    // }).then((res) => {
    //   console.log(res)
    //   this.setData({
    //     goodsdata: res.data.goodslist
    //   })
    // })   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log(this.data.data.groupInfo.groupId)
      return {
        title: '【仅剩' + this.data.needPeople + '个名额】快来' + this.data.data.goods[0].item[0].price + '元拼' + this.data.data.goods[0].item[0].goodsName,
        path: `pages/home/goodsDetail/grouppage/grouppage?groupId=${this.data.data.groupInfo.groupId}`,
          imageUrl: shareImg
      }
  },

  // 获取数据
  getData(options){
    let orderno = options.orderno
    let orderid = options.orderid
    console.log(orderno)
    this.setData({
      orderno: orderno ? orderno : '',
      orderid: orderid ? orderid : ''
    })
    let { userid = '', token = '' } = wx.getStorageSync('userinfo')
    this.setData({
      userid: userid,
      token: token
    })
    axios({
      url: '/order/orderGoodsDetail',
      data: {
        orderNo:  orderno,
        userid: userid,
        token: token
      }
    }).then((res) => {
      console.log(res)
      let orderStatus = res.data.data.orderState
      if (res.data.data.groupInfo){
        let needPeople = parseInt(res.data.data.groupInfo.groupText.replace(/[^0-9]/ig, "")) 
        let needPeopleicon = new Array( needPeople  )
        let totlegrouplength = res.data.data.groupInfo.avatarList.length + needPeople
        this.setData({
          needPeopleicon: needPeopleicon,
          needPeople: needPeople,
          totlegrouplength: totlegrouplength,
          movablewidth: totlegrouplength*120
        })
      }
      switch (orderStatus) {
        case '0':
          this.setData({
            statename: '待支付'
          })
          break
        case '1':
          this.setData({
            statename: '待发货'
          })
          break
        case '2':
          this.setData({
            statename: '交易关闭'
          })
          break
        case '5':
          this.setData({
            statename: '待收货'
          })
          break
        case '6':
          this.setData({
            statename: '商家待收货'
          })
          break
        case '7':
          this.setData({
            statename: '商家已收货'
          })
          break
        case '8':
          this.setData({
            statename: '商家已收货'
          })
          break
        case '9':
          this.setData({
            statename: '换货已发货'
          })
          break
        case '10':
          this.setData({
            statename: '交易完成'
          })
          break
        case '20':
          this.setData({
            statename: '超时关闭'
          })
          break
        case '21':    
          this.setData({
            statename: '用户手动取消'
          })
          break
        case '22':
          this.setData({
            statename: '待成团'
          })
          break
        default:
          break
      }
      this.setData({
        data: res.data.data,
        orderStatus: res.data.data.orderState,
        loglist: res.data.data.step? res.data.data.step: [],
        showbuyagain: res.data.isShopping
      })
      
      //拼团结束时间倒计时
      let groupclosetime = res.data.data.groupInfo ? res.data.data.groupInfo.endTime:''
      if (gettime(groupclosetime, 3)) {
        this.setData({
          grouptimetips: gettime(groupclosetime, 3).tips
        })
      }
      let grouptimer = setInterval(() => {
        if (gettime(groupclosetime, 3)) {
          this.setData({
            grouptimetips: gettime(groupclosetime, 3).tips
          })
        } else {
          clearInterval(grouptimer)
          //this.getData(options);
        }
      }, 1000)

      //订单状态倒计时
      let closetime = res.data.data.closeTime
      if (gettime(closetime, 3)) {
        this.setData({
          timetips: gettime(closetime, 3).tips
        })
      } else {
        this.setData({
          timetips: `00:00:00`
        })
      }
      let timer = setInterval(() => {
        if (gettime(closetime, 3)) {
          this.setData({
            timetips: gettime(closetime, 3).tips
          })
        } else {
          clearInterval(timer)
          this.setData({
            timetips: `00:00:00`
          })
        }
      }, 1000)
      //物流信息查询第一条高度  放在ajax内
      if (this.data.loglist.length) {
        wx.createSelectorQuery().select('.lastestlog').boundingClientRect().exec(res => {
          this.setData({
            loghideheight: res[0].height,
            initialheight: res[0].height
          })
        })
      }
      if (res.data.data.groupInfo){
        this.drawShareImg()
      }
    })
  },

  //复制剪切板
  copy (e) {
    let msg = e.currentTarget.dataset.msg
    wx.setClipboardData({
      data: msg,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon:"none"
        })
      }
    })
  },
  //打电话  商家或者退换货电话
  makephone (e) {
    let tel = e.currentTarget.dataset.tel
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },
  //打物流公司电话
  calllog (e) {
    let tel = e.currentTarget.dataset.tel
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },
  //物流展开
  showlog () {
    this.setData({
      loghideheight: 'auto'
    })
  },
  //物流收缩
  hidelog () {
    this.setData({
      loghideheight: this.data.initialheight
    })
  },
  //去评价页面
  goachieventlist (e) {
    let goodsid = e.currentTarget.dataset.goodsid
    console.log(goodsid)
    wx.navigateTo({
      url: `../../../home/goodsDetail/appraise/publish/publish?goods_id=${goodsid}`,
    })
  },
  //关闭退货提示弹窗
  returnboxclose () {
    this.setData({
      maskstate: false,
      returnbox: false
    })
  },
  //去退货申请页面
  goreturnrequest (e) {
    let {goodsId,specId,odid} = e.currentTarget.dataset
    console.log(odid)
      //待收货订单去这个页面
      if (this.data.data.orderState == 5 ){
        wx.navigateTo({
          url: `returnrequest/returnrequest?orderno=${this.data.orderno}&odid=${odid}&goodsId=${goodsId}&specId=${specId}`,
        })
      }else{
        this.setData({
          maskstate: true,
          returnbox: true
        })
      }
  },
  //去退货详情页
  goreturndetail(e) {
    let returnno = e.currentTarget.dataset.returnno
    console.log(returnno)
      wx.navigateTo({
          url: `../returndetail/returndetail?returno=${returnno}`,
      })
  },
  //去商品详情页
  gogoodsdetail (e) {
    let goodsid = e.currentTarget.dataset.goodsid
    console.log(goodsid)
    wx.navigateTo({
      url: `../../../home/goodsDetail/goodsDetail?linkId=${goodsid}`,
    })
  },
  //删除订单
  deleteorder (e) {
    wx.showModal({
      content: '确定要删除订单吗',
      success: (res) => {
        if (res.confirm) {
          console.log('用户点击确定')
          let orderno = e.currentTarget.dataset.orderno
          console.log(orderno)
          axios({
            url: '/order/del',
            data: {
              userid: this.data.userid,
              token: this.data.token,
              orderNo: orderno
            }
          }).then((res) => {
            console.log(res)
            wx.showToast({
              title: res.data.message,
              icon:"none"
            })
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];  // 获取上一页实例   可以获取上一页的数据并改变
            let data = prevPage.data.data
            console.log(data)
            data = data.filter(x => x.orderNo !== orderno)
            prevPage.setData({
              data: data
            })
            setTimeout(()=>{
              wx.navigateBack({
                delta: 1
              })
            },1500)
          })
        }
      }
    })
  },
  //投诉
  complain(e) {
    let orderno = e.currentTarget.dataset.orderno
    console.log(orderno)
    wx.navigateTo({
      url: `../complain/complain?orderno=${orderno}`
    })
  },
  //取消订单
  cancelorder (e) {
    console.log(e)
    wx.showModal({
      content: '确定要取消订单吗',
      success: (res) => {
        if (res.confirm) {
          console.log('用户点击确定')
          let orderno = e.currentTarget.dataset.orderno
          console.log(orderno)
          axios({
            url: '/order/cancel',
            data: {
              userid: this.data.userid,
              token: this.data.token,
              orderNo: orderno
            }
          }).then((res) => {
            console.log(res)
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];  // 获取上一页实例   可以获取上一页的数据并改变
            let data = prevPage.data.data
            data = data.filter(x => x.orderNo !== orderno)
            prevPage.setData({
              data: data
            })
            setTimeout(()=>{
              wx.navigateBack({
                delta: 1
              })
            },800)
          })
        }
      }
    })
  },
  //重新购买数据插入到购物车缓存 去购物车页面
  buyagain(e) {
    let orderno = e.currentTarget.dataset.orderno
    console.log(orderno)
    //可以重新购买的订单数据
    let thisdata = this.data.data.goodsInfo.filter(x => x.isSale == 1)
    console.log(thisdata)
    //如果有商品有库存的话 走购物车
    if (thisdata.length) {
      let obj = {}
      let specId = []
      let goodsId = []
      let num = []
      let goodsCheck = []
      for (let i = 0; i < thisdata.length; i++) {
        num.push(1)
        goodsCheck.push(1)
      }
      obj = {
        "specId": thisdata.map(x => x.specId),
        "goodsId": thisdata.map(x => x.goodsId),
        "num": num,
        "goodsCheck": goodsCheck
      }
      console.log(obj)
      //获取购物车数据
      let cartGoods = wx.getStorageSync('cartGoods')
      console.log(cartGoods)
      //如果购物车有数据 那就在最前面插入数据
      if (cartGoods) {
        let cartspecId = cartGoods.specId.split(',')
        let cartgoodsId = cartGoods.goodsId.split(',')
        let cartnum = cartGoods.num.split(',')
        let cartgoodsCheck = cartGoods.goodsCheck.split(',')
        for (let i = 0; i < thisdata.length; i++) {
          cartGoods.specId = cartspecId.unshift(obj.specId[i])
          cartGoods.goodsId = cartgoodsId.unshift(obj.goodsId[i])
          cartGoods.num = cartnum.unshift(obj.num[i])
          cartGoods.goodsCheck = cartgoodsCheck.unshift(obj.goodsCheck[i])
        }
        cartGoods = {
          specId: cartspecId.join(),
          goodsId: cartgoodsId.join(),
          num: cartnum.join(),
          goodsCheck: cartgoodsCheck.join()
        }
        //否则直接push
      } else {
        cartGoods = {
          specId: obj.specId.join(),
          goodsId: obj.goodsId.join(),
          num: obj.num.join(),
          goodsCheck: obj.goodsCheck.join()
        }
      }
      console.log(cartGoods)
      wx.setStorageSync('cartGoods', cartGoods)
      wx.switchTab({
        url: '../../../cart/cart',
      })
    }
  },
  //微信支付 直接走支付
  wxpay(e) {
    let orderno = e.currentTarget.dataset.orderno
    console.log(orderno)
    axios({
      url: '/pay/wxpay',
      data: {
        userid: this.data.userid,
        token: this.data.token,
        orderNo: orderno
      }
    }).then((res) => {
      console.log(res)
      wx.requestPayment({
        'timeStamp': res.data.timeStamp,
        'nonceStr': res.data.nonceStr,
        'package': res.data.package,
        'signType': res.data.signType,
        'paySign': res.data.paySign,
        'success': function (res) {
        },
        'fail': function (res) {
        }
      })
    })
  },
  //发起拼团分享
  groupwindowshow () {
    this.setData({
      groupwindowshow: true,
      maskstate:true
    })
  },
  //关闭拼团分享
  closegroupwindow () {
    this.setData({
      groupwindowshow: false,
      maskstate:false
    })
  },
  drawShareImg: function () {
        const ctx = wx.createCanvasContext('shareCanvas')
        ctx.setFillStyle('#FFF2E8')
        ctx.fillRect(0, 0, 375, 228)
        wx.downloadFile({
            url: this.data.data.goods[0].item[0].imgHttpsUrl,
            success: goodsImg => {
                if (goodsImg.statusCode === 200) {
                    ctx.drawImage(goodsImg.tempFilePath, 13, 13, 202, 202)
                    ctx.setFontSize(25)
                    ctx.setFillStyle('#C8431A')
                    ctx.fillText('￥', 235, 55)
                    ctx.setFontSize(36)
                    ctx.setFillStyle('#C8431A')
                    ctx.fillText(this.data.data.goods[0].item[0].price, 255, 55)
                    ctx.setFontSize(12)
                    ctx.setFillStyle('#9B9B99')
                    ctx.fillText('￥' + this.data.data.goods[0].item[0].taojjPrice, 240, 76)
                    ctx.beginPath()
                    ctx.moveTo(241, 72)
                    console.log('长度',String(this.data.data.goods[0].item[0].taojjPrice).length)
                    ctx.lineTo(251 + 9 * (String(this.data.data.goods[0].item[0].taojjPrice).length), 72)
                    ctx.setStrokeStyle('#9B9B99')
                    ctx.stroke()
                    ctx.setFontSize(13)
                    ctx.setFillStyle('#C8431A')
                    ctx.fillText('限时立省￥' + this.data.data.goods[0].item[0].savemoney, 240, 102)
                    let masterAvatar = this.data.data.groupInfo.avatarList.find(item => item.identity == 1).avatar;
                    wx.downloadFile({
                        url: masterAvatar,
                        success: masterAvatar => {
                            if (masterAvatar.statusCode === 200) {
                                ctx.drawImage(masterAvatar.tempFilePath, 258, 125, 30, 30)
                                ctx.drawImage('/images/home/ab.png', 253, 120, 38, 38)
                                ctx.drawImage('/images/home/q.png', 304, 124, 32, 32)
                                ctx.drawImage('/images/home/shareb1.png', 238, 170, 116, 34)
                                ctx.setFontSize(17)
                                ctx.setFillStyle('#fff')
                                ctx.fillText('立即拼团', 262, 193)
                                ctx.drawImage('/images/home/share_line.png', 0, 256, 375, 22)
                                ctx.setFontSize(17)
                                ctx.setFillStyle('#DE833D')
                                ctx.fillText('有品质的拼团App', 122, 274)
                                ctx.draw(true, () => {
                                    wx.canvasToTempFilePath({
                                        x: 0,
                                        y: 0,
                                        width: 375,
                                        height: 310,
                                        canvasId: 'shareCanvas',
                                        success: res => {
                                            shareImg = res.tempFilePath
                                            console.log('shareImg:', shareImg)
                                        }
                                    })
                                })
                            }
                        }
                    })
                }
            }
        })
    }
})